package com.moss.cloud.common.base.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.moss.cloud.common.core.utils.UserContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

@Component
public class CommonMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        String username = Optional.ofNullable(UserContextHolder.getUserInfo())
                .filter(userInfo -> UserContextHolder.getAuthStatus().equals(Boolean.TRUE))
                .map(userInfo -> UserContextHolder.getUsername())
                .orElse("system");
        this.setFieldValByName("createdBy", username, metaObject);
        this.setFieldValByName("updatedBy", username, metaObject);
        this.setFieldValByName("createdTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updatedTime", LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username = Optional.ofNullable(UserContextHolder.getUserInfo())
                .filter(userInfo -> UserContextHolder.getAuthStatus().equals(Boolean.TRUE))
                .map(userInfo -> UserContextHolder.getUsername())
                .orElse("system");
        this.setFieldValByName("updatedBy", username, metaObject);
        this.setFieldValByName("updatedTime", LocalDateTime.now(), metaObject);
    }
}
